<?php

require_once 'DbMgr.php';

class GeoMgr {

    static function savePosition($dbMgr, $lat, $lng, $address) {
        $address = addslashes($address);
        $query = "INSERT INTO geoloc(lat, lng, address) VALUES($lat, $lng, '$address')";
        $nb = $dbMgr->insert($query);
        return $nb;
    }

    static function loadAllPositions($dbMgr) {
        $query = "SELECT * FROM geoloc";
        $res = $dbMgr->select($query);
        $pos = self::formatPositions($res);
        return $pos;
    }

    static function formatPositions($res) {
        $i = 0;
        $positions = array();
        foreach ($res as $k => $v) {
            $id = $v["id"];
            $address = $v["address"];
            $lat = $v["lat"];
            $lng = $v["lng"];
            $d = $v["date_save"];
            $date = date("d/m/Y à H:m", strtotime($d));
            
            $positions[$i]["id"] = $id;
            $positions[$i]["date"] = $date;
            $positions[$i]["position"]["lat"] = $lat;
            $positions[$i]["position"]["lng"] = $lng;
            $positions[$i]["position"]["address"] = $address;
        
            $i++;
        }
        
        return $positions;
    }
    
    public static function showPositionsLeftList($positions)
    {
        $liste = "<div id=\"positions_chargees\">";/**/
        $liste .= "<h1>Positions enregistrées</h1>";
        //$liste .= "<input id='show_positions_button' type='submit' value='Afficher positions' onclick='showAllPositions(".$positions.");' />";
        $liste .= "<div id='liste_positions_chargees'>";
        
        $c = count($positions);
        for($i=0; $i<$c; $i++)
        {
            $liste .= "<div class='position'>";
            $liste .= "<input title='date_position_$i' class='date_position' readonly='readonly' value='".$positions[$i]["date"]."' />";
            $liste .= "<textarea title='adresse_position_$i' cols='1' rows='3' class=\"loaded_position_adress\" readonly='readonly' >".$positions[$i]["position"]["address"]."</textarea>";
            $liste .= "<input class=\"loaded_position_go\" type=\"submit\" value=\"Go\" onclick=\"showPosition(".$i.", ".$positions[$i]["position"]["lat"].",".$positions[$i]["position"]["lng"].",'".$positions[$i]["position"]["address"]."','".$positions[$i]["date"]."')\" />";
            $liste .= "</div>";
        }
        
        $liste .= "</div></div>";
        
        return $liste;
    }

}

?>
